//
//  HNFeeRecordController.m
//  JHFBaseProject
//
//  Created by 朱传正 on 2017/1/5.
//  Copyright © 2017年 好牛. All rights reserved.
//

#import "HNFeeRecordController.h"
#import "HNFeeRecordCell.h"

@interface HNFeeRecordController ()<UITableViewDelegate,UITableViewDataSource,HNFeeRecordCellDelegate>

@property (nonatomic,strong) UIButton *editBtn;

@property (nonatomic,strong)NSMutableArray *dataSource;

@property (nonatomic,strong)NSLock *threadLock;


@property (weak, nonatomic) IBOutlet UITableView *tableView;


@property (nonatomic,strong)UITextField *priceTF;


@property (nonatomic,strong)UIView *addView;


@property (nonatomic,assign)BOOL isAdd;

@end

@implementation HNFeeRecordController

-(void)setAddView{

        _addView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height)];
        [self.view addSubview:_addView];
        [_addView setHidden:YES];
        _addView.backgroundColor = RGBA(190, 190, 190, 0.5);
        UITapGestureRecognizer *tapGR=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenAction:)];
        [_addView addGestureRecognizer:tapGR];
        
        UIView *textView = [[UIView alloc]initWithFrame:CGRectMake(kScreen_Width/6, kScreen_Height/7, kScreen_Width*2/3,(kScreen_Width*2/3)*4/5 )];
        textView.backgroundColor = [UIColor whiteColor];
        [_addView addSubview:textView];
    
    CGFloat height = textView.frame.size.height;
    CGFloat width = textView.frame.size.width;
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, width, height - 46)];
    [textView addSubview:headView];
    
    UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,headView.frame.size.height/6,width,25)];
    nameLabel.numberOfLines = 1;
    nameLabel.clipsToBounds = YES;
    nameLabel.layer.cornerRadius = 4;
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.font = [UIFont boldSystemFontOfSize:24];
    nameLabel.backgroundColor = [UIColor whiteColor];
    nameLabel.textColor = [UIColor blackColor];
    nameLabel.text = @"图文咨询";
    [headView addSubview:nameLabel];
    
    UITextField *feeTF = [[UITextField alloc]initWithFrame:CGRectMake(width/2 - 55,headView.frame.size.height/2,55,35)];
    _priceTF = feeTF;
//    feeTF.keyboardType = UIKeyboardTypeNumberPad;
    feeTF.backgroundColor = [UIColor whiteColor];
    feeTF.textAlignment = NSTextAlignmentCenter;
    feeTF.borderStyle = UITextBorderStyleNone;
    feeTF.font = [UIFont systemFontOfSize:14];
    feeTF.placeholder = @"";
    [headView addSubview:feeTF];
    
    UILabel *promptLabel = [[UILabel alloc]initWithFrame:CGRectMake(width/2,headView.frame.size.height/2,width/2,35)];
    promptLabel.numberOfLines = 1;
    promptLabel.clipsToBounds = YES;
    promptLabel.layer.cornerRadius = 4;
    promptLabel.textAlignment = NSTextAlignmentLeft;
    promptLabel.font = [UIFont systemFontOfSize:14];
    promptLabel.backgroundColor = [UIColor whiteColor];
    promptLabel.textColor = RGBJ(125);
    promptLabel.text = @"元/小时";
    [headView addSubview:promptLabel];
    
    UILabel *lineLabel1 = [[UILabel alloc]initWithFrame:CGRectMake(width/2-50, headView.frame.size.height/2 + 30, 100, 1)];
    lineLabel1.backgroundColor = RGBJ(157);
    [headView addSubview:lineLabel1];
    
    
    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, height - 46, width, 1)];
    lineLabel.backgroundColor = RGBJ(241);
    [textView addSubview:lineLabel];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setFont:[UIFont systemFontOfSize:15]];
    [cancelBtn setBackgroundColor:[UIColor whiteColor]];
    [cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    cancelBtn.frame = CGRectMake(0, height-45, width/2, 45);
    [cancelBtn addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    [textView addSubview:cancelBtn];
    
    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn setFont:[UIFont systemFontOfSize:15]];
    [sureBtn setBackgroundColor:[UIColor whiteColor]];
    [sureBtn setTitleColor:RGB(67, 220, 45) forState:UIControlStateNormal];
    sureBtn.frame = CGRectMake(width/2, height-45, width/2, 45);
    [sureBtn addTarget:self action:@selector(sureAction:) forControlEvents:UIControlEventTouchUpInside];
    [textView addSubview:sureBtn];

    
    

}

-(void)hiddenAction:(UITapGestureRecognizer *)tagGR{
    [_addView setHidden:YES];
}

-(void)cancelAction:(UIButton *)btn{
    [_addView setHidden:YES];
}

-(void)sureAction:(UIButton *)btn{
    [self addFee];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"诊金设置";
     _dataSource = [[NSMutableArray alloc]init];
}

-(void)drawView{
    //添加点击按钮---添加一个按钮
    UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _editBtn = clickBtn;
    [clickBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [clickBtn setFont:[UIFont systemFontOfSize:15]];

    [clickBtn setTitleColor:RGBJ(80) forState:UIControlStateNormal];
    [clickBtn setTitleColor:RGBJ(80) forState:UIControlStateSelected];
    
    clickBtn.frame = CGRectMake(0,0,40,20);
    [clickBtn addTarget:self action:@selector(editAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:clickBtn];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    
//    NSMutableArray *dataSource = [NSMutableArray arrayWithObjects:@"免费咨询", @"图文资讯5元/小时",@"图文资讯20元/小时",@"图文资讯100元/小时", @"图文资讯10元/小时",@"图文资讯20元/小时",nil];
//    _dataSource = dataSource;
    
    [_tableView setBackgroundColor:[UIColor whiteColor]];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.bounces = NO;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    [self setAddView];
}

-(void)initData{
    [self getFeeRecordListData];
}

#pragma -mark 编辑
-(void)editAction:(UIButton *)btn{
    if ([_editBtn.titleLabel.text isEqualToString:@"完成"]) {
        for (NSInteger i = 10000; i < 10000 + _dataSource.count - 1; i ++ ) {
            UIButton *myButton = (UIButton *)[self.tableView viewWithTag:(i)];
            [myButton setHidden:YES];
        }
        [btn setTitle:@"编辑" forState:UIControlStateNormal];
    }else{
        for (NSInteger i = 10000; i < 10000 + _dataSource.count - 1; i ++ ) {
            UIButton *myButton = (UIButton *)[self.tableView viewWithTag:(i)];
            [myButton setHidden:NO];
        }
        
        [btn setTitle:@"完成" forState:UIControlStateNormal];
    }
    btn.selected = !btn.selected;
}


#pragma -mark TableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *feeRecordDic = _dataSource[indexPath.row];

    
    NSLog(@"----------fsdfds------------%@",feeRecordDic);
    
    
    static NSString *CellIdentifier = @"HNFeeRecordCell";
    
    HNFeeRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil]firstObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //防止cell复用
    
    if ([_editBtn.titleLabel.text isEqualToString: @"完成"]) {
        if (indexPath.row != _dataSource.count - 1) {
                    cell.cellDeleteBtn.hidden = NO;
        }
    }
    cell.cellDeleteBtn.tag = indexPath.row + 10000;

    cell.cellTitle.text = [NSString stringWithFormat:@"%@",[feeRecordDic objectForKey:@"goodsName"]];
    
    cell.indexPath = indexPath;
    cell.delegate = self;
    return cell;
}

#pragma mark - cell的方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == _dataSource.count-1) {
        [_addView setHidden:NO];
    }
}


#pragma mrak - HNFeeRecordCellDelegate
-(void)HNFeeRecordCell:(HNFeeRecordCell *)cell deleteIndexPath:(NSIndexPath *)indexPath{
    [_dataSource removeObjectAtIndex:indexPath.row];
     [self dalateFee:indexPath.row];
    
    [self.tableView reloadData];
    [self.tableView layoutIfNeeded];
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([self.editBtn isEqual:@"编辑"]) {
            for (NSInteger i = 10000; i < 10000 + _dataSource.count-1; i ++ ) {
                UIButton *myButton = (UIButton *)[self.tableView viewWithTag:(i)];
                [myButton setHidden:YES];
            }
        }else{
            for (NSInteger i = 10000; i < 10000 + _dataSource.count-1; i ++ ) {
                UIButton *myButton = (UIButton *)[self.tableView viewWithTag:(i)];
                [myButton setHidden:NO];
            }
        }
    });
    
   
}

#pragma mark - 获取诊金列表数据
-(void)getFeeRecordListData{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    [param setObject:@"1" forKey:@"goodsType"];
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_consultlist_mine parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSLog(@"responseObject = %@",responseObject);
        
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取诊金列表失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            NSDictionary *obj = [NSDictionary dictionaryWithDictionary:[data objectForKey:@"obj"]];
            
            NSLog(@"----ksadflksdl;gka-----%@",obj);
            
            NSMutableArray *objArr = [NSMutableArray arrayWithObject:[obj objectForKey:@"result"]][0];
            
            [_dataSource removeAllObjects];
            for (int i = 0; i < objArr.count; i++) {
                [_dataSource addObject:objArr[i]];
            }
            
            NSDictionary *lastDic = [NSDictionary dictionaryWithObjectsAndKeys:@"添加",@"goodsName",nil];
            NSLog(@"%@",lastDic);
            
             [_dataSource addObject:lastDic];
            
            [self.tableView reloadData];
        
           
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取诊金列表失败"];
    }];
    
}

#pragma mark - 添加诊金

-(void)addFee{
    
    CGFloat price = [[NSString stringWithFormat:@"%@",_priceTF.text] floatValue];
    if (price > 0 || [[NSString stringWithFormat:@"%@",_priceTF.text] isEqualToString:@"0"]) {
        
    }else{
        [self showHint:@"请输入价格"];
        return;
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    NSString *goodsName = [NSString stringWithFormat:@"图文咨询%@元/次",_priceTF.text];
    [param setObject:goodsName forKey:@"goodsName"];
    [param setObject:[NSString stringWithFormat:@"%@",_priceTF.text] forKey:@"shopPrice"];
    [param setObject:@"1" forKey:@"goodsType"];
    
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_consult_add parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSLog(@"responseObject = %@",responseObject);
        
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取诊金列表失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            
            
            _isAdd = YES;
            [self getFeeRecordListData];
            
            [self.addView setHidden:YES];
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取诊金列表失败"];
    }];
    
}


#pragma mark - 删除诊金

-(void)dalateFee:(NSInteger)row{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    
    NSString *goodsId = [NSString stringWithFormat:@"%@",[_dataSource[row - 1] objectForKey:@"goodsId"]];
    
    
    [param setObject:goodsId forKey:@"goodsId"];
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_consult_delete parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSLog(@"responseObject = %@",responseObject);
        
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取诊金列表失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
      
            [self getFeeRecordListData];

            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取诊金列表失败"];
    }];
    
}


@end
